package device

import (
	"context"
	"device-admin/config/mysql"
	"device-admin/internal/define"
	"device-admin/internal/models"
	"time"

	sharding "192.168.1.75/go-pkg/db-sharding"
	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/helper"
	"gorm.io/gorm"
)

// DeviceLog 任务执行记录
// robotID 机器编号,logCategory 日志分类，logType 日志类型
func DeviceLog(robotID string, logCategory, logType int, page, limit int) (interface{}, int64, error) {
	var (
		list []struct {
			models.DeviceLog
			LogCategoryName string `json:"log_category_name" gorm:"-"`
			LogTypeName     string `json:"log_type_name" gorm:"-"`
		}
		count int64
	)

	dbs := sharding.GetDB(context.Background(), mysql.NewDB(), models.DeviceLogTpl{}, time.Now().Unix()-3600*24*30, time.Now().Unix())
	if robotID == "" {
		return []string{}, 0, errorx.New("设备编号不能为空", -1)
	}
	db := dbs.QueryDB
	// 查询条件
	tx := db.Where("robot_id = ?", robotID)
	if logCategory >= 0 {
		tx = db.Where("log_category = ?", logCategory)
	}
	if logType >= 0 {
		tx = db.Where("log_type = ?", logType)
	}
	tx = tx.Session(&gorm.Session{})
	// 获取条数
	tx.Count(&count)
	if count <= 0 {
		return []string{}, 0, nil
	}

	// 查询记录
	helper.Gorm{}.Paginate(tx, page, limit).
		Select(
			"id",
			"robot_id",
			"log_category",
			"log_type",
			"content",
			"created_at",
		).
		Order("created_at desc").
		Find(&list)

	// 处理记录
	for index, record := range list {
		// 日志分类
		list[index].LogCategoryName = define.DeviceLogCategory[record.LogCategory]
		// 日志类型
		list[index].LogTypeName = define.DeviceLogType[record.LogType]
	}
	return list, count, nil
}

// AddDeviceLogLogic 增加设备日志/事件逻辑
func AddDeviceLog(records []models.DeviceLog) (int64, error) {
	db := mysql.NewDB()
	dbs := sharding.GetDB(context.Background(), db, models.DeviceLogTpl{}, time.Now().Unix(), time.Now().Unix())
	// 判定告警记录条数
	if len(records) <= 0 {
		return 0, errorx.New("记录不能为空", -1)
	}
	// 批量插入到数据库
	count := dbs.WriteDB.
		Create(&records).
		RowsAffected

	// 返回插入结果
	if count > 0 {
		return count, nil
	} else {
		return 0, errorx.New("新增失败")
	}
}
